﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Xml.Serialization;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections;

namespace PopShops
{
    public enum QueryMethod
    {
        DealType,
        Deals,
        Network,
        MerchantType,
        Merchant,
        Products
    }

    public abstract class Query
    {
        #region Private Fields

        private string MethodName { get; set; }
        private Type ObjectType { get; set; }

        #endregion

        #region Public Fields

        public QueryMethod Method { get; set; }
        public Stream QueryStream { get; set; }
        public object QueryData { get; set; }
        public StringDictionary filters { get; set; }
        public string QueryUrl { get; private set; }

        #endregion

        #region Ctor

        public Query(QueryMethod method, string methodname, Type type)
        {
            this.Method = method;
            this.MethodName = methodname;
            this.ObjectType = type;
            filters = new StringDictionary();
        }

        #endregion

        #region Methods

        public virtual void GetData()
        {
            WebClient web = new WebClient();
            QueryStream = web.OpenRead(GetQueryUrl());

            //object QueryData = new object();
            XmlSerializer serializer = new XmlSerializer(this.ObjectType);
            QueryData = serializer.Deserialize(QueryStream);
        }

        private string GetQueryUrl()
        {
            this.QueryUrl = string.Format("http://api.popshops.com/{0}/{1}/{2}.xml?", PsContext.Current.Version, PsContext.Current.AccountKey, this.MethodName);
            this.GenerateParams();
            if (filters.Count > 0)
            {
                foreach (DictionaryEntry pair in filters)
                    this.QueryUrl += pair.Key + "=" + pair.Value + "&";
            }

            return this.QueryUrl;
        }

        public abstract void GenerateParams();
        #endregion
    }
}